#include <iostream>
#include <ctime>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

int main(int argc, char *argv[])
{
    // 获取Ip和port
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server-ip server-port" << std::endl;
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    SockPtr sock = std::make_shared<TcpSocket>();
    if (!sock->BuildClientSocket(serverip, serverport))
    {
        std::cerr << "connect error" << std::endl;
        exit(1);
    }

    // 种子
    srand(time(nullptr) ^ getpid());
    const std::string opers = "+-*/%";

    std::string packagestreamqueue;
    while (true)
    {
        // 构建数据
        int x = rand() % 10;
        usleep(x * 1000);
        int y = rand() % 10;
        usleep(x * y * 100);
        char oper = opers[y % opers.size()];

        // 构建请求
        auto req = Factory::BuildRequestDefault();
        req->SetValue(x, y, oper);

        // 序列化
        std::string reqstr;
        req->Serialize(&reqstr);

        // 添加长度报头
        reqstr = Encode(reqstr);

        std::cout << "####################################" << std::endl;
        std::cout << "request string: \n"
                  << reqstr << std::endl;

        // 发送数据
        sock->Send(reqstr);

        while (true)
        {
            // 读取应答
            ssize_t n = sock->Recv(&packagestreamqueue);
            if (n <= 0)
                break;

            std::string package = Decode(packagestreamqueue);
            if (package.empty())
                continue;

            std::cout << "package: \n" << package << std::endl;

            // 6. 反序列化
            auto resp = Factory::BuildResponseDefault();
            resp->Deserialize(package);

            // 7. 打印结果
            resp->PrintResult();

            break;
        }
    }
    sock->Close();
    return 0;
}